<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>购物车 - Steam游戏商城</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <style>
        :root {
            --primary-color: #1b2838;
            --secondary-color: #2a475e;
            --accent-color: #66c0f4;
            --text-color: #c7d5e0;
            --light-bg: #223040;
            --dark-bg: #171a21;
            --button-color: #5c7e10;
            --button-hover: #79a816;
        }

        body {
            background-color: var(--primary-color);
            color: var(--text-color);
            font-family: 'Motiva Sans', sans-serif;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 15px;
        }

        /* 导航栏样式 */
        .navbar-steam {
            background-color: var(--dark-bg);
            border-bottom: 1px solid rgba(102, 192, 244, 0.1);
        }

        .navbar-brand {
            color: var(--accent-color);
            font-size: 24px;
            font-weight: bold;
        }

        .nav-link {
            color: var(--text-color);
            transition: color 0.2s;
        }

        .nav-link:hover {
            color: var(--accent-color);
        }

        .cart-badge {
            background-color: var(--button-color);
            color: white;
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 50%;
            position: absolute;
            top: -5px;
            right: -5px;
        }

        /* 购物车标题 */
        .cart-title {
            color: white;
            font-size: 28px;
            margin: 30px 0;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(102, 192, 244, 0.2);
        }

        /* 空购物车状态 */
        .empty-cart {
            background-color: var(--light-bg);
            border-radius: 5px;
            padding: 40px;
            text-align: center;
            margin: 20px 0;
        }

        .empty-cart-icon {
            font-size: 60px;
            color: rgba(102, 192, 244, 0.5);
            margin-bottom: 20px;
        }

        .empty-cart-title {
            color: white;
            font-size: 24px;
            margin-bottom: 10px;
        }

        .empty-cart-text {
            color: var(--text-color);
            margin-bottom: 20px;
        }

        .empty-cart-btn {
            background-color: var(--button-color);
            color: white;
            padding: 10px 20px;
            border-radius: 3px;
            text-decoration: none;
            transition: background-color 0.2s;
        }

        .empty-cart-btn:hover {
            background-color: var(--button-hover);
            color: white;
        }

        /* 购物车内容 */
        .cart-container {
            background-color: var(--light-bg);
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .cart-item {
            background-color: rgba(23, 26, 33, 0.3);
            border-radius: 3px;
            margin-bottom: 15px;
            padding: 15px;
            display: flex;
            align-items: center;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .cart-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 0 10px rgba(102, 192, 244, 0.1);
        }

        .game-image {
            width: 120px;
            height: 67px;
            border-radius: 3px;
            margin-right: 15px;
            object-fit: cover;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
        }

        .game-info {
            flex: 1;
            min-width: 0;
        }

        .game-title {
            color: white;
            font-size: 16px;
            margin-bottom: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .game-price {
            color: var(--accent-color);
            font-size: 18px;
            font-weight: bold;
        }

        .quantity-container {
            display: flex;
            align-items: center;
            margin: 0 15px;
        }

        .quantity-btn {
            background-color: var(--secondary-color);
            color: var(--text-color);
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 3px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .quantity-btn:hover {
            background-color: var(--accent-color);
            color: white;
        }

        .quantity-input {
            width: 50px;
            height: 30px;
            text-align: center;
            background-color: var(--dark-bg);
            color: white;
            border: 1px solid rgba(102, 192, 244, 0.2);
            margin: 0 5px;
            border-radius: 3px;
        }

        .subtotal {
            color: white;
            font-size: 18px;
            margin-right: 15px;
            min-width: 80px;
            text-align: right;
        }

        .remove-btn {
            color: #ff6b6b;
            cursor: pointer;
            transition: color 0.2s;
            margin-left: 15px;
        }

        .remove-btn:hover {
            color: #ff3838;
        }

        /* 总价区域 */
        .total-container {
            background-color: var(--secondary-color);
            border-radius: 3px;
            padding: 15px;
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .total-label {
            color: white;
            font-size: 20px;
            font-weight: bold;
        }

        .total-amount {
            color: var(--accent-color);
            font-size: 24px;
            font-weight: bold;
        }

        /* 操作按钮 */
        .cart-actions {
            display: flex;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .action-btn {
            margin-left: 15px;
            padding: 10px 25px;
            border-radius: 3px;
            font-weight: bold;
            transition: background-color 0.2s, transform 0.2s;
        }

        .action-btn:hover {
            transform: translateY(-2px);
        }

        .continue-btn {
            background-color: var(--secondary-color);
            color: var(--text-color);
        }

        .continue-btn:hover {
            background-color: rgba(42, 71, 94, 0.8);
            color: white;
        }

        .checkout-btn {
            background-color: var(--button-color);
            color: white;
        }

        .checkout-btn:hover {
            background-color: var(--button-hover);
            color: white;
        }

        /* 支付模态框 */
        .modal-content {
            background-color: var(--secondary-color);
            color: var(--text-color);
            border-radius: 5px;
            border: 1px solid rgba(102, 192, 244, 0.2);
        }

        .modal-header {
            border-bottom: 1px solid rgba(102, 192, 244, 0.2);
        }

        .modal-title {
            color: white;
            font-size: 20px;
        }

        .close {
            color: var(--text-color);
            opacity: 1;
        }

        .close:hover {
            color: white;
        }

        .payment-amount {
            color: var(--accent-color);
            font-size: 28px;
            font-weight: bold;
            margin: 20px 0;
        }

        .pay-button {
            background-color: var(--button-color);
            color: white;
            padding: 10px 30px;
            border-radius: 3px;
            font-weight: bold;
            transition: background-color 0.2s;
        }

        .pay-button:hover {
            background-color: var(--button-hover);
        }

        .payment-processing {
            color: var(--accent-color);
            margin-top: 20px;
        }

        .payment-success {
            color: #4cd137;
            font-weight: bold;
            margin-top: 20px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .cart-item {
                flex-direction: column;
                align-items: flex-start;
            }

            .game-image {
                margin-bottom: 10px;
            }

            .quantity-container {
                margin: 10px 0;
            }

            .subtotal {
                margin: 10px 0;
            }

            .remove-btn {
                margin: 10px 0 0 0;
            }

            .cart-actions {
                flex-direction: column;
            }

            .action-btn {
                margin-left: 0;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-steam">
    <div class="container">
        <a class="navbar-brand" href="#">Steam</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#">商店</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">社区</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">关于</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">支持</a>
                </li>
            </ul>
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="#">登录</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">注册</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link position-relative" href="#">
                        <i class="fa fa-shopping-cart"></i>
                        <span class="cart-badge" th:text="${#lists.size(cartItems)}">0</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- 主内容区 -->
<main class="container">
    <h1 class="cart-title">购物车</h1>

    <div class="cart-container">
        <!-- 空购物车状态 -->
        <div th:if="${#lists.isEmpty(cartItems)}" class="empty-cart">
            <i class="fa fa-shopping-cart empty-cart-icon"></i>
            <h3 class="empty-cart-title">您的购物车是空的</h3>
            <p class="empty-cart-text">浏览我们的游戏库，添加您喜欢的游戏到购物车</p>
            <a th:href="@{/games}" class="empty-cart-btn">
                <i class="fa fa-gamepad mr-2"></i>浏览游戏
            </a>
        </div>

        <!-- 购物车有商品 -->
        <div th:unless="${#lists.isEmpty(cartItems)}">
            <div th:each="item : ${cartItems}" class="cart-item">
                <img th:src="${item.game.imageUrl}" alt="游戏封面" class="game-image" th:alt="${item.game.name}">
                <div class="game-info">
                    <h4 class="game-title" th:text="${item.game.name}">游戏名称</h4>
                </div>
                <span class="game-price" th:text="${'¥' + #numbers.formatDecimal(item.game.price, 1, 2)}">¥99.00</span>
                <div class="quantity-container">
                    <div class="quantity-btn minus-btn" th:data-game-id="${item.game.id}">
                        <i class="fa fa-minus"></i>
                    </div>
                    <input
                            type="number"
                            min="1"
                            th:value="${item.quantity}"
                            name="quantity"
                            class="quantity-input"
                            th:id="'quantity-' + ${item.game.id}"
                            th:data-game-id="${item.game.id}"
                    >
                    <div class="quantity-btn plus-btn" th:data-game-id="${item.game.id}">
                        <i class="fa fa-plus"></i>
                    </div>
                </div>
                <span class="subtotal" th:text="${'¥' + #numbers.formatDecimal(item.game.price * item.quantity, 1, 2)}">¥99.00</span>
                <div class="remove-btn" th:data-game-id="${item.game.id}">
                    <i class="fa fa-trash"></i>
                </div>
            </div>

            <div class="total-container">
                <span class="total-label">总计:</span>
                <span class="total-amount" th:text="${'¥' + #numbers.formatDecimal(totalAmount, 1, 2)}">¥99.00</span>
            </div>

            <div class="cart-actions">
                <a th:href="@{/games}" class="action-btn continue-btn">
                    <i class="fa fa-arrow-left mr-2"></i>继续购物
                </a>
                <button id="checkoutBtn" class="action-btn checkout-btn">
                    <i class="fa fa-credit-card mr-2"></i>结算
                </button>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-dark py-4 mt-auto">
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <p class="text-muted">© 2025 Steam 游戏商城. 保留所有权利.</p>
            </div>
            <div class="col-md-6 text-md-right">
                <a href="#" class="text-muted mr-3">隐私政策</a>
                <a href="#" class="text-muted mr-3">使用条款</a>
                <a href="#" class="text-muted">帮助支持</a>
            </div>
        </div>
    </div>
</footer>

<!-- 支付模态框 -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog" aria-labelledby="paymentModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="paymentModalLabel">确认支付</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>您即将支付</p>
                <p class="payment-amount" id="modal-total-amount">¥99.00</p>
                <p>完成以下游戏的购买</p>
                <ul class="list-unstyled mt-3 mb-4" id="modal-game-list">
                    <!-- 动态生成游戏列表 -->
                </ul>
                <button id="payButton" class="pay-button">
                    <i class="fa fa-check-circle mr-2"></i>确认支付
                </button>
                <div id="paymentProcessing" style="display: none;" class="payment-processing">
                    <i class="fa fa-circle-o-notch fa-spin mr-2"></i>正在处理支付...
                </div>
                <p id="paymentResult" style="display: none;" class="payment-success"></p>
            </div>
            <div class="modal-footer">
                <button type="button" id="cancelButton" class="btn btn-secondary" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/decimal.js@10.4.0/decimal.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const quantityInputs = document.querySelectorAll('.quantity-input');
        const subtotalElements = document.querySelectorAll('.subtotal');
        const totalAmountElement = document.querySelector('.total-amount');
        const modalTotalElement = document.getElementById('modal-total-amount');
        const modalGameList = document.getElementById('modal-game-list');
        const checkoutBtn = document.getElementById('checkoutBtn');
        const paymentModal = new bootstrap.Modal(document.getElementById('paymentModal'));
        const payButton = document.getElementById('payButton');
        const paymentProcessing = document.getElementById('paymentProcessing');
        const paymentResult = document.getElementById('paymentResult');
        const plusButtons = document.querySelectorAll('.plus-btn');
        const minusButtons = document.querySelectorAll('.minus-btn');
        const removeButtons = document.querySelectorAll('.remove-btn');
        const cancelButton = document.getElementById('cancelButton');
        const closeButton = document.querySelector('.close');

        // 初始化计算总价
        calculateAndUpdateTotal();

        // 为数量输入框添加变化事件监听
        quantityInputs.forEach(input => {
            input.addEventListener('change', function() {
                // 确保数量不小于1
                if (parseInt(this.value) < 1) {
                    this.value = 1;
                }
                // 防抖处理，避免频繁计算
                debounce(calculateAndUpdateTotal, 300)();
            });
        });

        // 加号按钮点击事件
        plusButtons.forEach(button => {
            button.addEventListener('click', function() {
                const gameId = this.getAttribute('data-game-id');
                const input = document.getElementById('quantity-' + gameId);
                input.value = parseInt(input.value) + 1;
                calculateAndUpdateTotal();
            });
        });

        // 减号按钮点击事件
        minusButtons.forEach(button => {
            button.addEventListener('click', function() {
                const gameId = this.getAttribute('data-game-id');
                const input = document.getElementById('quantity-' + gameId);
                if (parseInt(input.value) > 1) {
                    input.value = parseInt(input.value) - 1;
                    calculateAndUpdateTotal();
                }
            });
        });

        // 移除按钮点击事件
        removeButtons.forEach(button => {
            button.addEventListener('click', function() {
                if (confirm('确定要从购物车中移除这个游戏吗？')) {
                    const gameId = this.getAttribute('data-game-id');
                    const form = document.createElement('form');
                    form.action = `/cart/remove/${gameId}`;
                    form.method = 'post';
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        });

        // 结算按钮点击事件
        checkoutBtn.addEventListener('click', function() {
            // 更新模态框中的总价
            modalTotalElement.textContent = totalAmountElement.textContent;

            // 生成模态框中的游戏列表
            modalGameList.innerHTML = '';
            const cartItems = document.querySelectorAll('.cart-item');
            cartItems.forEach(item => {
                const gameName = item.querySelector('.game-title').textContent;
                const quantity = item.querySelector('.quantity-input').value;
                const subtotal = item.querySelector('.subtotal').textContent;

                const li = document.createElement('li');
                li.className = 'mb-2';
                li.innerHTML = `
                        <div class="d-flex justify-content-between">
                            <span>${gameName}</span>
                            <span>${quantity} × ${subtotal}</span>
                        </div>
                    `;
                modalGameList.appendChild(li);
            });

            // 重置支付状态
            paymentProcessing.style.display = 'none';
            paymentResult.style.display = 'none';
            payButton.disabled = false;
            payButton.textContent = '确认支付';

            // 显示模态框
            paymentModal.show();
        });

        // 支付按钮点击事件
        payButton.addEventListener('click', function() {
            // 显示支付处理中状态
            paymentProcessing.style.display = 'block';
            payButton.disabled = true;
            payButton.textContent = '支付处理中...';

            // 模拟支付处理延迟
            setTimeout(function() {
                // 隐藏支付处理中，显示支付成功
                paymentProcessing.style.display = 'none';
                paymentResult.textContent = '支付成功！正在处理订单...';
                paymentResult.style.display = 'block';

                // 创建并提交表单到 /order/create
                const orderForm = document.createElement('form');
                orderForm.action = '/order/create';
                orderForm.method = 'post';

                // 添加CSRF令牌（如果应用需要）
                // const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                // const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
                // const csrfInput = document.createElement('input');
                // csrfInput.type = 'hidden';
                // csrfInput.name = csrfHeader;
                // csrfInput.value = csrfToken;
                // orderForm.appendChild(csrfInput);

                // 添加购物车项目数据
                const cartItems = document.querySelectorAll('.cart-item');
                cartItems.forEach((item, index) => {
                    const gameId = item.querySelector('.remove-btn').getAttribute('data-game-id');
                    const quantity = item.querySelector('.quantity-input').value;

                    const gameIdInput = document.createElement('input');
                    gameIdInput.type = 'hidden';
                    gameIdInput.name = `cartItems[${index}].game.id`;
                    gameIdInput.value = gameId;
                    orderForm.appendChild(gameIdInput);

                    const quantityInput = document.createElement('input');
                    quantityInput.type = 'hidden';
                    quantityInput.name = `cartItems[${index}].quantity`;
                    quantityInput.value = quantity;
                    orderForm.appendChild(quantityInput);
                });

                // 添加总价
                const totalAmount = totalAmountElement.textContent.replace('¥', '');
                const totalAmountInput = document.createElement('input');
                totalAmountInput.type = 'hidden';
                totalAmountInput.name = 'totalAmount';
                totalAmountInput.value = totalAmount;
                orderForm.appendChild(totalAmountInput);

                // 提交表单
                document.body.appendChild(orderForm);
                orderForm.submit();
            }, 2000); // 模拟2秒的支付处理时间
        });

        // 取消按钮点击事件 - 直接重定向（虽然data-dismiss会关闭模态框，但先添加点击事件确保兼容性）
        if (cancelButton) {
            cancelButton.addEventListener('click', function() {
                goBackToCart();
            });
        }

        // 关闭按钮（×）点击事件
        if (closeButton) {
            closeButton.addEventListener('click', function() {
                goBackToCart();
            });
        }

        // 模态框隐藏事件监听 - 确保无论哪种方式关闭模态框都重定向
        const paymentModalElement = document.getElementById('paymentModal');
        if (paymentModalElement) {
            paymentModalElement.addEventListener('hidden.bs.modal', function() {
                goBackToCart();
            });
        }

        // 计算并更新小计和总价
        function calculateAndUpdateTotal() {
            let total = new Decimal(0);

            subtotalElements.forEach((subtotalElement, index) => {
                const priceElement = subtotalElement.closest('.cart-item').querySelector('.game-price');
                const quantityInput = subtotalElement.closest('.cart-item').querySelector('.quantity-input');

                if (priceElement && quantityInput) {
                    // 提取价格和数量
                    const price = new Decimal(priceElement.textContent.replace('¥', ''));
                    const quantity = new Decimal(quantityInput.value);

                    // 计算小计
                    const subtotal = price.mul(quantity).toFixed(2);
                    subtotalElement.textContent = `¥${subtotal}`;

                    // 累加总价
                    total = total.add(subtotal);
                }
            });

            // 更新总价
            totalAmountElement.textContent = `¥${total.toFixed(2)}`;
        }

        // 重定向到购物车页面
        function goBackToCart() {
            window.location.href = '/cart';
        }

        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function() {
                const context = this;
                const args = arguments;
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(context, args), wait);
            };
        }
    });
</script>
</body>
</html>